<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2019/12/9
 * Time: 14:40
 */

namespace app\api\controller;


use think\Db;

class Order extends Base
{
    private $user_id;
    private $page;
    private $create_time;
    private $order_number;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
        $this->order_number = date('YmdHis') . rand(1000, 9999);
        $time = input('time');
        $value = input('value');
        $reqKey = input('reqKey');
        $auth = $this->checkAll($this->user_id,$time,$value,$reqKey);
        if($auth == 112){
            echo json_encode(['status'=>301,'msg'=>$this->otherLogin]);
            exit;
        }elseif($auth == 110){
            echo json_encode(['status' => 302, 'msg' => $this->frost]);
            exit;
        }elseif($auth == 2111){
            echo json_encode(['status' => 303, 'msg' => $this->del]);
            exit;
        }
    }
    
    /**
     * 订单列表
     * @return \think\response\Json
     * order_type  0 全部  1 待付款  2 已付款  3 已发货  4 已收货  5 已关闭  6 已退款
     */
    public function orderList(){
        $order_type = input('order_type');
        $order = $this->order($order_type, 1);
        foreach($order as $k => $v){
            $order[$k]['order_expressage_num'] = ltrim($v['order_expressage_num'], ',');
        }
        if($order){
            return json(['status' => 200, 'msg' => $order]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 订单详情
     * @return \think\response\Json
     * order_id    订单ID
     */
    public function orderDetail(){
        $order_id = input('order_id');
        $order_status = Db::table('up_order')->where('order_id', $order_id)->value('order_status');
        // 如果是待付款订单，需要判断付款剩余时间
        if($order_status == 1){
            $this->changeNoPayStatus($order_id);
        }
        $detail = Db::table('up_order')
            ->join('up_goods', 'order_goods_id = goods_id', 'left')
            ->field('order_id, order_status, order_user_phone, order_user_name, order_sheng, order_shi, 
            order_qu, order_addrerss, goods_name, goods_thumb, goods_price, order_num, order_price, 
            order_number, order_pay_type, order_time, order_pay_time, order_send_time, order_over_time, 
            order_expressage_company, order_expressage_num, order_freight, order_goods_id')
            ->where('order_id', $order_id)
            ->find();
        $detail['order_expressage_num'] = ltrim($detail['order_expressage_num'], ',');
        return json(['status' => 200, 'msg' => $detail]);
    }
    
    /**
     * 订单操作
     * @return \think\response\Json
     * status        订单状态  1 删除订单   2 取消订单  3 确认收货  4 关闭订单
     * order_id      订单ID
     */
    public function orderStatus(){
        $status = input('status'); //  1 删除订单  2 取消订单  3 确认收货  4 关闭订单
        $order_id = input('order_id');
        $order_info = Db::table('up_order')
            ->field('order_goods_id, order_num, order_status')
            ->where('order_id', $order_id)
            ->find();
        
        if($status == 1){
            if($order_info['order_status'] == 5 || $order_info['order_status'] == 4){
                $res = Db::table('up_order')->delete($order_id);
            }else{
                return json(['status' => 0, 'msg' => '该订单不可以删除']);
            }
        }elseif($status == 2){
            if($order_info['order_status'] != 1){
                return json(['status' => 0, 'msg' => '该订单不可以取消']);
            }
            // 释放库存
            $this->freeStock($order_info['order_goods_id'], $order_info['order_num']);
            $res = Db::table('up_order')->where('order_id', $order_id)->setField('order_status', 5);
        }elseif($status == 3){
            if($order_info['order_status'] != 3){
                return json(['status' => 0, 'msg' => '该订单不可以确认收货']);
            }
            $res = Db::table('up_order')
                ->where('order_id', $order_id)
                ->update(['order_status' => 4, 'order_over_time' => date('Y-m-d H:i:s')]);
        }else{
            if($order_info['order_status'] != 1){
                return json(['status' => 0, 'msg' => '该订单不可以关闭']);
            }
            // 释放库存
            $this->freeStock($order_info['order_goods_id'], $order_info['order_num']);
            $res = Db::table('up_order')->where('order_id', $order_id)->setField('order_status', 5);
        }
        if($res){
            if($status == 3) {
                $this->OrderNotice(2, $order_id);
            }
            return json(['status' => 200, 'msg' => '操作成功']);
        }else{
            return json(['status' => 0, 'msg' => '操作失败']);
        }
    }
    
    /**
     * 订单状态的数量
     * @return \think\response\Json
     */
    public function orderNum(){
        $noPayNum = $this->order(1, 2); // 待付款
        $nosendNum = $this->order(2, 2); // 待发货
        $noConfirmNum = $this->order(3, 2); // 待收货
        return json(['status' => 200, 'noPayNum' => $noPayNum, 'noSendNum' => $nosendNum, 'noConfirmNum' => $noConfirmNum]);
    }
    
    /**
     * 付款失败订单插入消息&推送
     * order_id    订单ID
     */
    public function falsePayOrder(){
        $order_id = input('order_id');
        $this->OrderNotice(1, $order_id);
        return json(['status' => 200, 'msg' => $order_id]);
    }
    
    /**
     * 物流
     * @return \think\response\Json
     * order_id     订单ID
     */
    public function wuLiu(){
        $order_id = input('order_id');
        // 物流信息
        $wuliu = Db::table('up_order')
            ->field('order_expressage_company, order_expressage_num, order_goods_thumb')
            ->where('order_id', $order_id)
            ->find();
        $code = ltrim($wuliu['order_expressage_num'], ',');
        $wuliu['order_expressage_num'] = $code;
        //*********** 获取快递公司编码
        $auto_url = 'http://www.kuaidi100.com/autonumber/auto?';
        $auto_data = [
            'num' => $code,
            'key' => config('kd.zhnkey')
        ];
        $auto_data = http_build_query($auto_data);
        $auto_url_http = $auto_url . $auto_data;
        $request_auto = kd_http($auto_url_http); // 智能判断返回的数据
        if(isset($request_auto['returnCode'])){
            return json(['status' => 0, 'msg' => $request_auto['message']]);
        }else{
            //***************** 获取快递信息
            $search_url = 'http://poll.kuaidi100.com/poll/query.do';
        
            $post_data = [];
            $post_data["customer"] = config('kd.customer');
            $key = config('kd.key');
            if(!empty($request_auto)){
                $com = $request_auto[0]['comCode'];
                $post_data["param"] = '{"com":"' . $com . '","num":"' . $code . '"}';
                $post_data["sign"] = md5($post_data["param"].$key.$post_data["customer"]);
                $post_data["sign"] = strtoupper($post_data["sign"]);
                $post_data = http_build_query($post_data);
                $search_data = kd_http($search_url, $post_data);
                // 返回失败信息
                if(isset($search_data['returnCode'])){
                    return json(['status' => 0, 'msg' => $search_data['message'], 'wuliu' => $wuliu]);
                }else{
                    return json(['status' => 200, 'msg' => $search_data['data'], 'wuliu' => $wuliu]);
                }
            }else{
                return json(['status' => 200, 'msg' => [], 'wuliu' => $wuliu]);
            }
        }
    }
    
    /**
     * 订单列表
     * @param $showType      类型  0 全部  1 待付款  2 已付款  3 已发货  4 已收货  5 已关闭  6 已退款
     * @param array $range   使用途径   1 列表   2 数量
     * @param array $where   条件
     * @return false|\PDOStatement|string|\think\Collection
     */
    private function order($showType, $range, $where = []){
        if($showType != 0){
            $where['order_status'] = $showType;
        }
        $where['order_user_id'] = $this->user_id;
        
        $order = Db::table('up_order')
            ->join('up_goods', 'order_goods_id = goods_id', 'left')
            ->where($where);
        if($range == 1){
            $order = $order->field('order_id, order_number, order_num, order_status, order_price, goods_name, 
            goods_thumb, goods_price, order_expressage_company, order_expressage_num')
                ->page($this->page, 10)
                ->order('order_time desc')
                ->select();
        }else{
            $order = $order->count();
        }
        return $order;
    }
    
    /**
     * 修改30分钟未付款的订单
     * @param $order_id   订单ID
     */
    private function changeNoPayStatus($order_id){
        $now_time = time();
        $order = Db::table('up_order')
            ->field('order_goods_id, order_num, order_time')
            ->where('order_id', $order_id)
            ->find();
        $diff = $now_time - strtotime($order['order_time']);
        // 30分钟
        if($diff >= 30*60){
            // 关闭订单
            Db::table('up_order')->where('order_id', $order_id)->setField('order_status', 5);
            // 释放库存
            $this->freeStock($order['order_goods_id'], $order['order_num']);
        }
    }
    
    /**
     * 订单推送&消息表
     * @param $type       1 付款失败    2 已收货
     * @param $order_id   订单ID
     */
    private function OrderNotice($type, $order_id){
        if($type == 1){
            $title = '您有一笔订单还未付款，请尽快支付订单，点击查看详情';
            $send_type = 2;
        }else{
            $title = '您的包裹已签收，如有疑问请联系我们，祝您生活愉快！点击查看物流';
            $send_type = 4;
        }
        // 消息表
        $notice = [
            'notice_type' => 2,
            'notice_cate' => 1,
            'notice_subject_id' => $order_id,
            'notice_title' => $title,
            'notice_user' => ',0,' . $this->user_id . ',',
            'notice_read_user' => ',0,',
            'notice_del_user' => ',0,',
            'notice_time' => $this->create_time,
        ];
        Db::table('up_notice')->insert($notice);
        try{
            $send_user = (string)$this->user_id;
            $this->Jpush(1, $send_user, $title, ['send_type' => $send_type, 'order_id' => $order_id]);
        }catch(\Exception $e){
            
        }
    }
}